//
//  BDHomeSearchViewController.m
//  BadBoy
//
//  Created by wen on 2017/4/7.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDHomeSearchViewController.h"
#import "BDHomeSearchResultViewController.h"

@interface BDHomeSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDHomeSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = ASLocalizedString(@"搜索");
    [self layoutViews];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    [self.textField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.textField resignFirstResponder];
}

- (void)layoutViews{
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 283 / 375.0 * kBDScreenWidth, 30)];
    _textField.backgroundColor = [UIColor colorWithHexString:@"#555555"];
    _textField.tintColor = [UIColor colorWithHexString:@"#bbbbbb"];
    _textField.font = [UIFont systemFontOfSize:13];
    _textField.placeholder = ASLocalizedString(@"输入搜索关键字");
    _textField.textColor = [UIColor whiteColor];
    _textField.delegate = self;
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 5;
    _textField.centerX = self.view.width / 2.0 - 10;
    
    [_textField setValue:[UIColor colorWithHexString:@"#bbbbbb"] forKeyPath:@"_placeholderLabel.textColor"];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 30)];
    leftView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imageView.image = [UIImage imageNamed:@"sousuo"];
    [leftView addSubview:imageView];
    imageView.right = leftView.width - 5;
    imageView.centerY = leftView.height / 2.0;
    _textField.leftView = leftView;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    self.navigationItem.titleView = _textField;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"搜索")style:UIBarButtonItemStylePlain target:self action:@selector(searchbuttonAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)searchbuttonAction{
    [self.textField resignFirstResponder];
    [self.textField resignFirstResponder];
    if (self.textField.text.length == 0) {
        [self.view alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"没有输入搜索内容")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
            [self.textField becomeFirstResponder];
        }];
    }else{
        if ([self.datasource containsObject:self.textField.text]) {
            [self.datasource removeObject:self.textField.text];
        }
        [self.datasource insertObject:self.textField.text atIndex:0];
        [self.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"homeSearch.plist"] atomically:YES];
        BDHomeSearchResultViewController *resultVC = [[BDHomeSearchResultViewController alloc] init];
        resultVC.keyword = self.textField.text;
        resultVC.typeString = self.typeString;
        [self.navigationController pushViewController:resultVC animated:YES];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchCell"];
        
        UIButton *deletedButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deletedButton.size = CGSizeMake(15, 15);
        [deletedButton setEnlargeEdgeWithTop:12 right:12 bottom:12 left:12];
        [deletedButton setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [cell.contentView addSubview:deletedButton];
        deletedButton.centerY = cell.height / 2.0;
        deletedButton.right = kBDScreenWidth - 15;
        [[deletedButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self.datasource removeObjectAtIndex:indexPath.row];
            [self.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"homeSearch.plist"] atomically:YES];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
    cell.textLabel.text = self.datasource[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.layer.borderWidth = 0.5;
    cell.layer.borderColor = kBDColorGray.CGColor;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.textField.text = self.datasource[indexPath.row];
    [self searchbuttonAction];
}

- (UIView *)customHeaderView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 94 + 10 + 15 + 6)];
    header.backgroundColor = [UIColor clearColor];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = ASLocalizedString(@"搜索历史");
    label1.textColor = [UIColor colorWithHexString:@"#767676"];
    label1.font = [UIFont systemFontOfSize:14];
    label1.size = CGSizeMake([label1.text widthWithFont:label1.font], label1.font.pointSize+1);
    label1.top =  15;
    label1.left = 10;
    label1.backgroundColor = [UIColor clearColor];
    [header addSubview:label1];
    
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    clearButton.size = CGSizeMake(20, 20);
    [clearButton setBackgroundImage:[UIImage imageNamed:@"qingchu"] forState:UIControlStateNormal];
    clearButton.right = kBDScreenWidth - 10;
    clearButton.centerY = label1.centerY;
    [header addSubview:clearButton];
    [clearButton addTarget:self action:@selector(clearButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    header.height = label1.bottom + 10;
    return header;
}

- (void)clearButtonAction:(UIButton *)button{
    [self.view alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"是否要删除历史记录")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"确定")] clickBlock:^(NSInteger index) {
        if (index ==1) {
            //删除
            [self.datasource removeAllObjects];
            [self.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"homeSearch.plist"] atomically:YES];
            [self.tableView reloadData];
        }
    }];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.tableHeaderView = [self customHeaderView];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray arrayWithContentsOfFile:[DocumentPath stringByAppendingPathComponent:@"homeSearch.plist"]];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
